<template>
    <div class="app-container">
      <el-form ref="formRef" :model="form" :rules="rules">
        <el-row class="el-top">
          <el-col :span="4">
            <el-form-item class="ml20 mt8 mr20" label="入库方式:" prop="importClass">
              <el-select v-model="form.importClass" :disabled="!isImport" placeholder="请选择入库方式"
                         @change="importClassClick">
                <el-option v-for="(dict, index) in typeList" :key="dict.dictValue" :label="dict.dictLabel"
                           v-show="dict.dictValue !='12'"
                           :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item v-if="form.importClass === '0'" class="mt8" label="供货单位:" prop="supplier">
              <material-supplier :id="form.supplier" ref="firmName" :placeholder="'请选择供货单位'"
                        style="float: left; width: 180px"
                        @supplierChange="supplierChange"/>
            </el-form-item>
            <el-form-item v-else class="mt8" label="供货单位:" prop="storageFrom">
              <material-storage-info ref="materialStorageDeptRef" :material-fromLevel-str="materialFromLevelStr"
                                 :org-id="queryParams.orgId"
                                 :value="form.storageFrom" :value-storage-id="form.storageFrom"
                                 class="import-master" style="width: 180px"
                                 @materialStorageChange="storageFromClick"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item class="ml20 mt8" label="入库科室:" prop="storageId">
              <material-storage-dept ref="storageIdDeptRef" :org-id="queryParams.orgId"
                                 :value-storage-id="form.storageId" disabled="disabled" style="width: 180px"
                                 class="import-master" @materialStorageChange="storageIdClick"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item class="ml20 mt8" label="付款方式:">
              <el-select v-model="form.accountType" clearable placeholder="请选择付款方式" style="width: 50%">
                <el-option v-for="dict in dictDataMap['drug_payment_type']" :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <span class="el-form-item__label ml10 mt5">进价合计：<span class="fz19 font-color-red mr5"> {{
              tradePriceTotal
            }}</span>元</span>
          <span class="el-form-item__label ml10 mt5">售价合计：<span class="fz19 font-color-red mr5"> {{
              retailPriceTotal
            }}</span>元</span>
        </el-row>
        <el-row>
          <!-- 入库编辑列表 -->
          <el-table :border="true" :data="form.detailList" :header-cell-style="$headerCellStyle"
                    header-cell-class-name="requiredClass">
            <el-table-column :align="'center'" fixed="left" label="消耗品名称" min-width="168px" prop="materialName">
              <template #default="scope">
                <el-form-item :prop="'detailList.' + scope.$index + '.itemInfo'" :rules="rules.itemInfo"
                              class="table-form-margin">
                  <!-- 入库消耗品检索 -->
                  <el-input v-if="scope.row.isShow" v-model="scope.row.materialName"
                            @focus="isShowItemNameFocus(scope.$index, scope.row)">
                  </el-input>
                  <automatic-completion v-else ref="itemAutomatic" :dict-array="dictArray" :table-body-list="tableBodyList"
                                        :table-head-list="tableHeadList" :title="itemTitle" :leftSpan="24" :rightSpan="0"
                                        :right-div-show-type="'material'" :width="1000" style="width: 100%"
                                        @itemNameInput="itemNameInput" @rowClick="rowClick($event, 0)"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="进货价" prop="purchasePrice"
                             width="100px">
              <template #default="scope">
                <el-form-item :prop="'detailList.' + scope.$index + '.purchasePrice'" :rules="rules.purchasePrice"
                              class="table-form-margin">
                  <el-input v-model="scope.row.purchasePriceShow"
                            @blur="tradePriceBlue(scope.$index)"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="比例" prop="discount"
                             width="90px">
              <template #default="scope">
                <el-form-item :prop="'detailList.' + scope.$index + '.discount'" :rules="rules.discount"
                              class="table-form-margin">
                  <el-select ref="ratio" v-model="scope.row.discount" filterable placeholder="请选择比例"
                             style="width: 100%"
                             @change="tradePriceBlue(scope.$index)">
                    <el-option v-for="dict in dictDataMap['price_ratio']" :key="dict.dictValue"
                               :label="dict.dictLabel"
                               :value="dict.dictValue"></el-option>
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="零售价" prop="retailPrice"
                             width="100px">
              <template #default="scope">
                <el-form-item :prop="'detailList.' + scope.$index + '.retailPrice'"
                              :rules="rules.retailPrice"
                              class="table-form-margin">
                  <el-input v-model="scope.row.retailPriceShow"
                            @blur="tradePriceBlue(scope.$index)"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="批号" prop="batchNo"
                             width="110px">
              <template #default="scope">
                <el-form-item :prop="'detailList.' + scope.$index + '.batchNo'" :rules="rules.batchNo"
                              class="table-form-margin">
                  <el-input v-model="scope.row.batchNo"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库数量" prop="quantity"
                             width="130px">
              <template #default="scope">
                <el-form-item :prop="'detailList.' + scope.$index + '.quantity'" :rules="rules.quantity"
                              class="table-form-margin">
                  <el-input v-model="scope.row.quantity" clearable>
                    <template #append>
                      <dict-data-tag :options="dictDataMap['spec_unit']"
                                     :value="scope.row.currentUnits"/>
                    </template>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="生产日期" prop="produceDate"
                             width="135px">
              <template #default="scope">
                <el-form-item :prop="'detailList.' + scope.$index + '.produceDate'"
                              :rules="rules.produceDate">
                  <el-date-picker v-model="scope.row.produceDate" :disabled-date="disabledProduceDateFunc" clearable
                                  placeholder="生产日期" style="width: 100%" type="date"
                                  value-format="YYYY-MM-DD"
                                  @change="produceDateChange(scope.$index)">
                  </el-date-picker>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="有效期" prop="expireDate"
                             width="135px">
              <template #default="scope">
                <el-form-item :prop="'detailList.' + scope.$index + '.expireDate'"
                              :rules="rules.expireDate">
                  <el-date-picker v-model="scope.row.expireDate" clearable placeholder="有效期"
                                  style="width: 100%"
                                  type="date" value-format="YYYY-MM-DD"
                                  @change="expireDateChange(scope.$index)">
                  </el-date-picker>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="货柜" prop="location"
                             width="100px">
              <template #default="scope">
                <el-form-item class="table-form-margin">
                  <el-input v-model="scope.row.location"/>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂家" prop="firmName"
                             width="160px"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="消耗品编号" prop="materialCode"
                             width="120px"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格" prop="currentSpec"
                             width="100px"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装数量" prop="packageNum"
                             width="100px"/>
            
            <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" header-align="center"
                             label="操作"
                             width="60px">
              <template #default="scope">
                <el-tooltip class="item" content="添加" effect="dark" placement="top">
                  <el-button circle type="primary" @click="handleAdd">
                    <template #icon>
                      <i-ep-plus/>
                    </template>
  
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
  
        </el-row>
        <el-row class="mt5">
          <el-col :span="1.5" class="mr10">
            <span class="mr20">待入库消耗品</span>
            <el-button style="margin-bottom: 3px" type="primary" @click="temporaryStorage">
              <template #icon>
                <i-ep-FolderOpened/>
              </template>
              暂存
            </el-button>
          </el-col>
          <el-col :span="1.5" class="mr10">
            <el-button :disabled="buttonLoading" type="info" @click="temporaryStorageTableClick">
              <template #icon>
                <i-ep-memo/>
              </template>
              暂存列表
            </el-button>
          </el-col>
          <el-col :span="2" class="mr10">
            <el-button :disabled="buttonLoading" type="success" @click="lastSave">
              <template #icon>
                <i-ep-FolderOpened/>
              </template>
              确认入库
            </el-button>
          </el-col>
          <el-col :span="8">
            <span style="color: #fd0101;font-size: 13px">入库发票号：</span>
            <el-input v-model="form.invoiceNo" clearable style="width: 180px"/>
          </el-col>
          <el-table v-adaptive="120" :border="true" :data="form.detailListSave" :header-cell-style="$headerCellStyle"
                    highlight-current-row>
            <el-table-column :align="'center'" fixed="left" label="序号" prop="index" width="100px">
              <template #default="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column :align="'center'" fixed="left" label="消耗品名称" min-width="168px" prop="materialName"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="进货价" prop="purchasePrice"
                             width="100px">
              <template #default="scope">
                {{ scope.row.purchasePriceShow }}
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="比例" prop="discount"
                             width="100px"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="零售价" prop="retailPrice"
                             width="100px">
              <template #default="scope">
                {{ scope.row.retailPriceShow }}
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="批号" prop="batchNo"
                             width="120px"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库数量" prop="quantity"
                             width="90px">
              <template #default="scope">
                <div>
                  <dict-data-tag :options="dictDataMap['spec_unit']" :value="scope.row.currentUnits"
                                 class="mb-10 mr10"
                                 style="float: right"/>
                  <div class="mr20" style="float: right; font-weight: bold">
                    {{ scope.row.quantity }}
                  </div>
                </div>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="生产日期" prop="produceDate"
                             width="140px">
              <template #default="scope">
                <span>{{ $parseTime(scope.row.produceDate, "{y}-{m}-{d}") }}</span>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="有效期" prop="expireDate"
                             width="140px">
              <template #default="scope">
                <span>{{ $parseTime(scope.row.expireDate, "{y}-{m}-{d}") }}</span>
              </template>
            </el-table-column>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="货柜" prop="location"
                             width="100px"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="厂家" prop="firmName"
                             width="160px"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="消耗品编号" prop="materialCode"
                             width="120px"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="规格" prop="currentSpec"
                             width="100px"/>
            <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装数量" prop="packageNum"
                             width="80px"/>
            
            <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="right" header-align="center"
                             label="操作"
                             width="90px">
              <template #default="scope">
                <el-tooltip class="item" content="编辑" effect="dark" placement="left">
                  <el-button v-hasPerm="['base:drugImportMaster:edit']" circle type="success"
                             @click="handleUpdate(scope.row, scope.$index)">
                    <template #icon>
                      <i-ep-edit/>
                    </template>
  
                  </el-button>
                </el-tooltip>
                <el-tooltip class="item" content="删除" effect="dark" placement="top">
                  <el-button v-hasPerm="['base:drugImportMaster:remove']" circle type="danger"
                             @click="handleDelete(scope.row, scope.$index)">
                    <template #icon>
                      <i-ep-delete/>
                    </template>
  
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <el-dialog v-model="open" :close-on-click-modal="false" :title="'暂存列表'" append-to-body width="94%"
                 @close="temporaryStorageClose">
        <el-row :gutter="10">
          <el-col :span="10">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>入库主记录（点击列表可查看入库消耗品明细）</span>
              </div>
              <div class="mb20">
                <el-table :border="true" :data="stagingList" :header-cell-style="$headerCellStyle" height="400"
                          @row-click="stagingMaster">
                  <el-table-column :align="'center'" class-name="small-padding fixed-width" fixed="left"
                                   header-align="center" label="操作" width="80px">
                    <template #default="scope">
                      <el-tooltip class="item" content="引入"
                                  effect="dark"
                                  placement="top">
                        <el-button circle type="primary" @click.stop="bringIn(scope.row)">
                          <template #icon>
                            <i-ep-edit/>
                          </template>
                        </el-button>
                      </el-tooltip>
                      <el-tooltip class="item" content="删除"
                                  effect="dark"
                                  placement="top">
                        <el-button circle type="danger" @click.stop="deleteMaster(scope.row)">
                          <template #icon>
                            <i-ep-delete/>
                          </template>
                        </el-button>
                      </el-tooltip>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="采购商"
                                   prop="supplierName"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="出库库房"
                                   prop="storageFromName"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库库房"
                                   prop="storageName"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库方式"
                                   min-width="75px"
                                   prop="importClass">
                    <template #default="scope">
                      <dict-data-tag :options="dictDataMap['material_storage_type']"
                                     :value="scope.row.importClass"/>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库时间"
                                   min-width="130px"
                                   prop="importDate"/>
                  <el-table-column :align="'left'" :show-overflow-tooltip="true" label="应付款(总价)"
                                   min-width="90px"
                                   prop="accountReceivable"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="操作人"
                                   min-width="90px"
                                   prop="createByName">
                  </el-table-column>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="操作时间"
                                   min-width="90px"
                                   prop="createTime">
                  </el-table-column>
                </el-table>
                <pagination v-show="total > 0" v-model:limit="queryParams.pageSize"
                            v-model:page="queryParams.pageNum"
                            :total="total" @pagination="getList"/>
              </div>
            </el-card>
          </el-col>
          <el-col :span="14">
            <el-card class="box-card">
              <div slot="header" class="clearfix">
                <span>入库单明细</span>
              </div>
              <div class="mb20">
                <el-table :border="true" :data="stagingListDetail" :header-cell-style="$headerCellStyle" height="400">
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="序号"
                                   min-width="60px"
                                   prop="itemNo"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="消耗品编号"
                                   min-width="100px"
                                   prop="materialCode"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="消耗品名称"
                                   min-width="180px"
                                   prop="materialName">
                    <template #default="scope">
                      <span class="fz14 fw-bold">{{ scope.row.materialName }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装数量"
                                   min-width="90px"
                                   prop="packageNum"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="包装规格"
                                   min-width="120px"
                                   prop="packageSpec"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="入库数量"
                                   min-width="90px"
                                   prop="quantity">
                    <template #default="scope">
                      <div>
                        <dict-data-tag :options="dictDataMap['spec_unit']"
                                       :value="scope.row.packSize === '1' ? scope.row.minUnits :scope.row.packageUnits"
                                       class="mb-10 mr10" style="float: right"/>
                        <div class="mr20" style="float: right; font-weight: bold">
                          {{ scope.row.quantity }}
                        </div>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="进货价"
                                   min-width="90px"
                                   prop="purchasePriceShow"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="零售价"
                                   min-width="90px"
                                   prop="retailPriceShow"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="生产批号"
                                   min-width="90px"
                                   prop="batchNo"/>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="生产日期"
                                   min-width="90px"
                                   prop="produceDate">
                    <template #default="scope">
                      <span>{{ $parseTime(scope.row.produceDate, "{y}-{m}-{d}") }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column :align="'center'" :show-overflow-tooltip="true" label="有效期"
                                   min-width="90px"
                                   prop="expireDate">
                    <template #default="scope">
                      <span>{{ $parseTime(scope.row.expireDate, "{y}-{m}-{d}") }}</span>
                    </template>
                  </el-table-column> 
                </el-table>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </el-dialog> 
    </div>
  </template>
  
  <script lang="ts" setup>
  import {
    addMaterialImportMaster,
    delMaterialImportMaster,
    getAutoMaterialPriceInfo,
    selectPageMaterialImportMaster,
  } from "@/api/material/materialImportMaster";
  import {listMaterialImportDetail}from "@/api/material/materialImportDetail";
  import {getStoreroomDistinguish} from "@/api/material/materialInoutClass";
  import {quantityNumber, retailPriceV, tradePriceV} from "@/utils/myRules";
  import {useUserStoreHook} from "@/store/modules/user";
  import {useDictStoreHook} from "@/store/modules/dict";
  import {materialImportList, jsonStrInObj} from "@/utils/autoComplete";

  

  const formRef = ref();
  const storageIdDeptRef = ref();
  const materialStorageDeptRef = ref();
  const useUserStore = useUserStoreHook();
  const {proxy} = getCurrentInstance() as any;
  const dictStore = useDictStoreHook();
  const dictDataMap = ref(
    dictStore.isTypeGetData("material_storage_type", "drug_payment_type", "price_ratio", "spec_unit")
  );
  const currentSelectDept = proxy.$currentSelectDept
  // 科室等级字符串
  const materialFromLevelStr = ref<String>('')
  // 按钮loading
  const buttonLoading = ref(false);
  // 登录用户信息
  const userInfo = <UserInfoBusi>useUserStore.user.userInfo;
  // 追溯码弹出框是否打开
  const trackCodesEnterOpen = ref(false);
  // 追溯码弹列表数据
  const trackCodesRow = ref<any>({});
  // 追溯码弹出框input内容
  const trackCodesInput = ref<String>("")
  // 追溯码点击行号
  const currentIndex = ref(-1)
  const itemAutomatic = ref();
  // 暂存列表
  const stagingList = ref<any>([]);
  // 暂存入库明细列表
  const stagingListDetail = ref<any>([]);
  // 判断是否可入库
  const isImport = ref(true);
  // 总条数
  const total = ref(0);
  // 是否显示暂存列表弹出层
  const open = ref(false);
  // 入库方式list
  const typeList = ref<any>([]);
  // 表单参数
  const form = ref<any>({
    importClass: "",
    isStaging: "Y",
    accountType: "1",
    supplier: "",
    storageFrom: "",
    invoiceNo: "",
    detailList: [
      {
        expireDate: "",
        discount: "1",
        itemInfo: "",
        infoId: "",
        materialName: "",
        materialCode: "",
        orgId: "",
        orgName: "",
        packageSpec: "",
        packageUnits: "",
        purchasePrice: "",
        retailPrice: "",
        firmId: "",
        firmName: "",
        packageNum: "",
        materialPriceId: "",
        trackCodes: ""
      },
    ],
    detailListSave: [],
  });
  // 暂存列表查询参数
  const detailQuery = ref<any>({
    pageNum: 1,
    pageSize: 10,
    masterId: "",
  });
  const queryParams = ref<any>({
    pageNum: 1,
    pageSize: 10,
    orgId: undefined,
    orgName: undefined
  });
  // 项目选择自动补全窗体名称
  const itemTitle = ref("消耗品选择");
  // 项目选择自动补全表格表头
  const tableHeadList = ref<any>(jsonStrInObj(materialImportList));
  // 项目选择自动补全表格数据
  const tableBodyList = ref<any>([]);
  // 项目选择自动补全字典数组
  const dictArray = ref(["spec_unit"]);
  // 进价合计
  const tradePriceTotal = ref(0);
  // 零售价合计
  const retailPriceTotal = ref(0);
 
  // 表单校验
  const rules = ref({
    itemInfo: [{required: true, message: "消耗品名称不能为空", trigger: "blur"}],
    purchasePrice: [{required: true, validator: tradePriceV, trigger: "change"}],
    retailPrice: [{required: true, validator: retailPriceV, trigger: "change"}],
    produceDate: [{required: true, message: "生产日期不能为空", trigger: "blur"}],
    expireDate: [{required: true, message: "有效期不能为空", trigger: "blur"}],
    batchNo: [{required: true, message: "批号不能为空", trigger: "blur"}],
    importClass: [{required: true, message: "入库方式不能为空", trigger: "change"}],
    discount: [{required: true, message: "比例不能为空", trigger: "change"}],
    // supplier: [
    //     {required: true, message: "供货单位不能为空", trigger: "blur"}
    // ],
    // storageFrom: [
    //     {required: true, message: "供货单位不能为空", trigger: "blur"}
    // ],
    storageId: [{required: true, message: "入库科室不能为空", trigger: "blur"}],
    quantity: [{required: true, validator: quantityNumber, trigger: "blur"}],
  });
  
  if (userInfo.orgId) {
    queryParams.value.orgId = userInfo.orgId;
    queryParams.value.orgName = userInfo.orgName;
  }
  if (!currentSelectDept) {
    ElMessage.error("请选择库存库房后，再进行入库操作。");
  } else {
    isImport.value = true;
    form.value.storageId = currentSelectDept;
  }
  
  /**
   * 入库方式
   */
  function importClassClick(value: string) {
    form.value.storageFrom = currentSelectDept
    const index = typeList.value.findIndex((item: any) => {
      return item.dictValue == value;
    });
    if (index > -1) {
      materialFromLevelStr.value = typeList.value[index].fromLevel + ","
    }
  }
  
  /** 项目名称自动补全检索 */
  function itemNameInput(event, _value) {
    form.value.itemName = event;
    getAutoMaterialPriceInfoFun();
  }
  
  /** 入库药品检索 */
  function getAutoMaterialPriceInfoFun() {
    const param = {
      storageId: form.value.storageFrom || currentSelectDept,
      orgId: queryParams.value.orgId,
      itemInfo: form.value.itemName,
    };
    getAutoMaterialPriceInfo(param).then((res) => {
      tableBodyList.value = res.data;
      console.log(tableBodyList.value)
      itemAutomatic.value.init();
    });
  }
  
  /** 消耗品自动补全点击事件 */
  function rowClick(obj, index) {
    console.log(obj)
    nextTick(() => {
      if (obj) {
        form.value.detailList[index].isShow = true
        form.value.detailList[index].itemInfo = obj.materialName;
        form.value.detailList[index].infoId = obj.materialInfoId;
        form.value.detailList[index].materialName = obj.materialName;
        form.value.detailList[index].materialCode = obj.materialCode;
        form.value.detailList[index].orgId = obj.orgId;
        form.value.detailList[index].orgName = userInfo.orgName;
        form.value.detailList[index].packageSpec = obj.packageSpec;
        form.value.detailList[index].currentSpec = obj.currentSpec;
        form.value.detailList[index].currentUnits = obj.currentUnits;
        form.value.detailList[index].packageUnits = obj.packageUnits;
        form.value.detailList[index].units = obj.units;
        form.value.detailList[index].purchasePrice = obj.tradePrice;
        form.value.detailList[index].purchasePriceShow = obj.tradePrice;
        form.value.detailList[index].retailPriceShow = obj.retailPrice;
        form.value.detailList[index].retailPrice = obj.retailPrice;
        form.value.detailList[index].packSize = obj.packSize;
        form.value.detailList[index].discount = "1";
        form.value.detailList[index].firmId = obj.firmId;
        form.value.detailList[index].firmName = obj.firmName;
        form.value.detailList[index].packageNum = obj.packageNum;
        form.value.detailList[index].materialPriceId = obj.materialPriceId;
        itemAutomatic.value.closePopover();
        itemAutomatic.value.itemNameFocus();
      }
    });
  }
  
  /**
   * 自动补全上边input获得焦点事件   待测试
   * @param _index
   * @param row
   */
  function isShowItemNameFocus(_index: number, row: any) {
    row.isShow = false
    nextTick(() => {
      itemAutomatic.value.init()
      itemAutomatic.value.setItemName(row.materialName)
      itemAutomatic.value.focusInput()
    })
  }
  
  
  /** 生产日期校验 */
  function disabledProduceDateFunc(time) {
    return time.getTime() > Date.now();
  }
  
  /** 有效期校验 */
  // function disabledExpireDateFunc(time) {
  
  // }
  
  /** 生产日期点击事件 */
  function produceDateChange(index) {
    //1095  三年
    const newDate = proxy.$addDay(1095, new Date(form.value.detailList[index].produceDate));
    if (newDate) {
      form.value.detailList[index].expireDate = proxy.$parseTime(newDate, "{y}-{m}-{d}");
    }
    if (
      proxy.$getDaysDiff(
        form.value.detailList[index].expireDate,
        new Date(form.value.detailList[index].produceDate)
      ) < 90
    ) {
      return ElMessage.error("消耗品有效期小于90天。");
    }
  }
  
  /** 有效期点击事件 */
  function expireDateChange(index) {
    if (
      proxy.$getDaysDiff(
        form.value.detailList[index].expireDate,
        new Date(form.value.detailList[index].produceDate)
      ) < 90
    ) {
      return ElMessage.error("消耗品有效期小于90天。");
    }
  }
  
  /** 供货商点击事件 */
  function supplierChange(obj) { 
    form.value.supplier = obj.supplierId;
    form.value.storageFrom = undefined;
  }
  
  /** 科室选择事件 */
  function storageFromClick(obj) { 
    form.value.storageFrom = obj.storageId;
    form.value.supplier = undefined;
  }
  
  function storageIdClick(obj) { 
    form.value.storageId = obj.storageId || obj.id;
    form.value.storageName = obj.storageName || obj.name;
  }
  
  // 监控科室是否改变，并查询入库方式
  watch(() => currentSelectDept, () => {
    getStoreroomDistinguishFun()
  
  }, {deep: true, immediate: true})
  
  /** 根据科室id 出入库类型获取库房对应的出入库方式 */
  function getStoreroomDistinguishFun() {
    if (currentSelectDept) {
      typeList.value = [];
      let param = {
        storageCode: currentSelectDept,
        orgId: queryParams.value.orgId,
        inoutType: "1",
        dictType: "material_storage_type",
      };
      getStoreroomDistinguish(param).then((res: any) => {
        res.data.forEach((item: any) => {
          item.sysDictData.fromLevel = item.fromLevel
          typeList.value.push(item.sysDictData);
        });
        // 判断默认库房是 药库类型 ，如果是默认供货单位为 "供应商"
        if (res.data[0].storageType === "1") {
          form.value.importClass = "0";
        }
      });
    }
  }
  
  /** 查询入库暂存列表 */
  function getList() {
    selectPageMaterialImportMaster(queryParams.value).then((response: any) => {
      stagingList.value = response.rows;
      total.value = response.total;
    });
  }
  
  async function getListDetail() {
    await listMaterialImportDetail(detailQuery.value).then((response: any) => {
      stagingListDetail.value = response.data;
      stagingListDetail.value.forEach((item: any) => {
        item.purchasePriceShow = item.packSize === "1" ? item.purchasePriceMin : item.purchasePrice;
        item.retailPriceShow = item.packSize === "1" ? item.retailPriceMin : item.retailPrice;
      })
    });
    console.log(stagingListDetail.value)
    return stagingListDetail.value;
  }
  
  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }
  
  // 表单重置
  function reset() {
    form.value = {
      id: undefined,
      documentNo: undefined,
      storageId: undefined,
      importDate: undefined,
      supplier: undefined,
      storageFrom: undefined,
      accountReceivable: undefined,
      accountPayed: undefined,
      additionalFee: undefined,
      importClass: undefined,
      accountType: undefined,
      accountIndicator: undefined,
      acctDate: undefined,
      acctOperator: undefined,
      tally: undefined,
      tallyDate: undefined,
      tallyOperator: undefined,
      orgId: undefined,
      voucherNo: undefined,
      recoveryDocuNo: undefined,
      delFlag: undefined,
      createBy: undefined,
      createTime: undefined,
      updateBy: undefined,
      updateTime: undefined,
      remarks: undefined,
    };
  }
  
  function temporaryStorageClose() {
    // 暂存列表
    stagingList.value = [];
    // 暂存入库明细列表
    stagingListDetail.value = [];
    open.value = false;
  }
  
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }
  
  /** 重置按钮操作 */
  function resetQuery() {
    handleQuery();
  }
  
  /**
   * 暂存列表 引入
   * @param row
   */
  async function bringIn(row) {
    if (form.value.detailListSave.length > 0) {
      return ElMessage.error("已添加列表存在未保存的数据，请暂存或者入库后再引入当前数据");
    }
    detailQuery.value.masterId = row.importMasterId;
    let stagingListDetail = await getListDetail();
    form.value.importClass = row.importClass;
    form.value.isStaging = row.isStaging;
    form.value.accountType = row.accountType;
    form.value.invoiceNo = row.invoiceNo;
    form.value.documentNo = row.documentNo;
    form.value.importMasterId = row.importMasterId;
    // 设置入库科室
    nextTick(() => {
      storageIdDeptRef.value.setValue(row.storageId);
    });
    // 设置供货单位
    if (row.importClass === "0") {
      form.value.supplier = row.supplier;
    } else {
      nextTick(() => {
        importClassClick(row.importClass)
        materialStorageDeptRef.value.setValue(row.storageFrom);
        form.value.storageFrom = row.storageFrom;
        form.value.storageId = row.storageId;
      });
    }
    // 设置入库明细
    stagingListDetail.forEach((obj) => {
      let detail: any = {};
      detail.itemInfo = obj.materialName;
      detail.importDetailId = obj.importDetailId;
      detail.infoId = obj.infoId;
      detail.masterId = obj.masterId;
      detail.materialName = obj.materialName;
      detail.materialCode = obj.materialCode;
      detail.orgId = obj.orgId;
      detail.orgName = obj.orgName;
      detail.packageSpec = obj.packageSpec;
      detail.currentSpec = obj.packageSpec;
      detail.packageUnits = obj.packageUnits;
      detail.currentUnits = obj.packSize === "1" ? obj.minUnits : obj.packageUnits;
      detail.purchasePrice = obj.purchasePrice;
      detail.purchasePriceMin = obj.purchasePriceMin;
      detail.purchasePriceShow = obj.packSize === "1" ? obj.purchasePriceMin : obj.purchasePrice;
      detail.discount = obj.discount;
      detail.retailPrice = obj.retailPrice;
      detail.retailPriceMin = obj.retailPriceMin;
      detail.retailPriceShow = obj.packSize === "1" ? obj.retailPriceMin : obj.retailPrice;
      detail.packageNum = obj.packageNum;
      detail.materialPriceId = obj.materialPriceId;
      detail.packSize = obj.packSize;
      // packSize === '1' 小包装  packSize === '2' 大包装
      detail.quantity = obj.quantity;
      detail.produceDate = obj.produceDate;
      detail.expireDate = obj.expireDate;
      detail.batchNo = obj.batchNo;
      detail.location = obj.location;
      detail.firmName = obj.firmName;
      detail.firmId = obj.firmId; 
      detail.supplier = form.value.supplier
      detail.trackCodes = obj.trackCodes
      form.value.detailListSave.push(detail);
    });
    computeSum();
    open.value = false;
  }
  
  /** 已开药品明细计算合计 */
  function computeSum() {
    // 进价合计
    let tradePriceTotalThis: number = 0;
    // 零售价合计
    let retailPriceTotalThis: number = 0;
    form.value.detailListSave.forEach((item: any) => {
      let quantity = item.quantity;
      let tradePriceThis = 0.00
      let retailPriceThis = 0.00
      // if (item.packSize === "2") {
      //   tradePriceThis = item.tradePrice
      //   retailPriceThis = item.retailPrice
      // } else {
      //   tradePriceThis = item.tradePriceMin
      //   retailPriceThis = item.retailPriceMin
      // }
      tradePriceTotalThis += Number(item.purchasePriceShow) * quantity;
      retailPriceTotalThis += Number(item.retailPriceShow) * quantity;
    });
    // 进价合计
    tradePriceTotal.value = Number(tradePriceTotalThis.toFixed(2));
    // 零售价合计
    retailPriceTotal.value = Number(retailPriceTotalThis.toFixed(2));
  }
  
  /** 暂存列表主记录点击事件 */
  async function stagingMaster(row, _index) {
    detailQuery.value.masterId = row.importMasterId;
    await getListDetail();
  }
  
  /** 新增按钮操作 */
  function handleAdd() {
    if (!form.value.importClass) {
      return ElMessage.error("入库方式不能为空");
    }
    if (!form.value.storageId) {
      return ElMessage.error("入库科室不能为空");
    }
    if (form.value.importClass === "0" && !form.value.supplier) {
      return ElMessage.error("供货单位不能为空");
    }
    if (form.value.importClass !== "0" && !form.value.storageFrom) {
      return ElMessage.error("供货单位不能为空");
    }
    // form.detailList.push({discount: '1', retailPrice: ''})
    (formRef.value as any).validate((valid) => {
      // importInvoiceElMessageBox()
      if (valid) {
        if (form.value.detailList[0].packSize === '2') {
          form.value.detailList[0].retailPriceMin = (form.value.detailList[0].retailPriceShow / form.value.detailList[0].packageNum).toFixed(4)
          form.value.detailList[0].purchasePriceMin = (form.value.detailList[0].purchasePriceShow / form.value.detailList[0].packageNum).toFixed(4)
        } else {
          form.value.detailList[0].retailPriceMin = form.value.detailList[0].retailPriceShow
          form.value.detailList[0].purchasePriceMin = form.value.detailList[0].purchasePriceShow
          form.value.detailList[0].retailPrice = (form.value.detailList[0].retailPriceShow * form.value.detailList[0].packageNum).toFixed(2)
          form.value.detailList[0].purchasePrice = (form.value.detailList[0].purchasePriceShow * form.value.detailList[0].packageNum).toFixed(2)
        }
        console.log(form.value.detailList[0])
        // 添加到已编辑列表
        form.value.detailListSave.push(form.value.detailList[0]);
        // 删除当前编辑列表数据
        form.value.detailList = [{expireDate: "", discount: "1"}];
        nextTick(() => {
          itemAutomatic.value.setItemName("");
        });
        computeSum();
        //清空追溯码弹出框input内容
        trackCodesInput.value = ""
      }
    });
    tableBodyList.value = [];
  }
  
  /** 进价焦点消失 、计算售价*/
  function tradePriceBlue(index) {
    // 进价
    let purchasePrice = form.value.detailList[index].purchasePriceShow;
    form.value.detailList[index].purchasePrice = form.value.detailList[index].purchasePriceShow
    if (purchasePrice) {
      // 获取点击行的行号index
      const ratioIndex = dictDataMap.value["price_ratio"].findIndex((item) => {
        return item.dictValue === form.value.detailList[index].discount;
      });
      if (ratioIndex > -1) {
        // 设置本行售价
        form.value.detailList[index].retailPrice = (
          purchasePrice * Number(dictDataMap.value["price_ratio"][ratioIndex].dictLabel)
        ).toFixed(4);
        form.value.detailList[index].retailPriceShow = form.value.detailList[index].retailPrice
        form.value.detailList[index].retailPriceShow = form.value.detailList[index].retailPrice
      }
    }
  }
  
  /** 修改按钮操作 */
  function handleUpdate(row, index) {
    if (form.value.detailList[0].itemInfo) {
      ElMessageBox.confirm(
        "编辑列表存在未保存的药品数据，继续编辑将会替换编辑列表中的数据，确定要继续嘛？",
        "提示",
        {
          confirmButtonText: "替换编辑",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          form.value.detailList = [{expireDate: "", discount: "1"}];
          form.value.detailList[0] = row;
          form.value.detailListSave.splice(index, 1);
          nextTick(() => {
            itemAutomatic.value.setItemName(row.materialName);
          });
        })
        .catch(() => {
        });
    } else {
      form.value.detailList = [{expireDate: "", discount: "1"}];
      console.log("row", row)
      form.value.detailList[0] = row;
      form.value.detailListSave.splice(index, 1);
      nextTick(() => {
        itemAutomatic.value.setItemName(row.materialName);
      });
    }
  }
  
  /** 暂存 */
  function temporaryStorage() {
    form.value.isStaging = "Y";
    save();
  }
  
  /** 最终提交 */
  function lastSave() {
    form.value.isStaging = "N";
    save();
  }
  
  function save() {
    if (form.value.detailListSave.length <= 0) {
      return ElMessage.error("没有需要入库的消耗品明细，不能提交");
    }
    // if (!form.value.invoiceNo) {
    //   return ElMessage.error("入库收据号为空，不能提交");
    // }
    ElMessageBox.confirm(
      `${form.value.isStaging === "Y" ? "确认要进行暂存吗？" : "确认要进行入库吗？"}`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }
    )
      .then(() => {
        form.value.orgId = queryParams.value.orgId;
        form.value.orgName = queryParams.value.orgName;
        form.value.accountReceivable = tradePriceTotal.value;
        form.value.accountPayed = tradePriceTotal.value;
        buttonLoading.value = true;
        let i = 0;
        form.value.detailListSave.forEach((item: any) => {
          i++;
          item.produceDate = proxy.$parseTime(item.produceDate, "{y}-{m}-{d} {h}:{i}:{s}");
          item.expireDate = proxy.$parseTime(item.expireDate, "{y}-{m}-{d} {h}:{i}:{s}");
          item.itemNo = i;
        });
        buttonLoading.value = true;
        addMaterialImportMaster(form.value).then(() => {
          // 清空入库发票号
          form.value.invoiceNo = ""
          if (form.value.isStaging === "Y") {
            ElMessage.success("暂存成功");
          } else {
            ElMessage.success("入库成功");
          }
          form.value.detailListSave = [];
          form.value.importMasterId = ''
          retailPriceTotal.value = 0.00
          tradePriceTotal.value = 0.00
        })
          .finally(() => {
            buttonLoading.value = false;
          });
      })
      .catch(() => {
        ElMessage.info("已取消操作");
      });
  }
  
  /** 暂存列表弹出框 */
  function temporaryStorageTableClick() {
    open.value = true;
    queryParams.value.isStaging = "Y"; 
    getList();
  }
  
  /** 删除按钮操作 */
  function handleDelete(row, index) {
    // const ids = row.id || ids;
    ElMessageBox.confirm('是否确认删除消耗品"' + row.materialName + '"的数据？', {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
      .then(() => {
        form.value.detailListSave.splice(index, 1);
        ElMessage.success("删除成功");
      })
      .catch(() => {
      });
  }
  
  
  function deleteMaster(row: any) {
    ElMessageBox.confirm('是否确认删除暂存数据？',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {
      delMaterialImportMaster(row.importMasterId).then(() => {
        getList();
        stagingListDetail.value = []
        ElMessage.success("删除成功");
      })
    })
  }
  
  
  </script>
  
  <script lang="ts">
  export default {
    name: "MaterialImportMaster"
  }
  </script>
  
  <style scoped>
  :deep(.el-top) {
    background-color: rgb(212, 211, 211);
    border-radius: 5px 5px 5px 5px;
    margin: -5px 3px 5px 3px;
    height: 44px;
  }
  
  :deep(.dept-tree-label) {
    margin-right: -77px;
    margin-top: 6px;
    width: 18%;
  }
  
  :deep(.vue-treeselect__input-container) {
    height: 26px !important;
  }
  
  .account_type {
    font-weight: bold;
    color: rgb(30, 30, 30);
    float: left;
    width: 6%;
    /*margin-top: 6px;*/
  }
  
  :deep(.cell .el-tag) {
    margin: 0 -10px 0 -10px;
  }
  
  :deep(.el-input__wrapper) {
    background-color: #ff000017;
  }
  
  </style>
  